<?php
/**
 * @project kkzc
 * @date 2015-7-10
 * @author xialei <xialeistudio@gmail.com>
 */

namespace app\module\api\controllers;

use app\models\Message;
use yii\data\ActiveDataProvider;
use yii\web\ForbiddenHttpException;


/**
 * 消息控制器
 * @author xialei <xialeistudio@gmail.com>
 * Class MessageController
 * @package app\module\api\controllers
 */
class MessageController extends BaseController
{
    public $modelClass = 'app\models\Message';

    /**
     * @author xialei <xialeistudio@gmail.com>
     * @param string $action
     * @param Message $model
     * @param array $params
     * @throws \yii\web\ForbiddenHttpException
     */
    public function checkAccess($action, $model = null, $params = [])
    {
        if (\Yii::$app->admin->isGuest && $model != null && $model->user_id != \Yii::$app->user->id && !\Yii::$app->request->isOptions) {
            throw new ForbiddenHttpException();
        }
    }

    public function actions()
    {
        $actions = parent::actions();
        $actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
        return $actions;
    }

    public function prepareDataProvider()
    {
        $state = \Yii::$app->request->getQueryParam('state', null);
        $query = Message::find()->where(['user_id' => \Yii::$app->user->id])->orderBy(['state' => SORT_ASC, 'message_id' => SORT_DESC]);
        if ($state != null) {
            $query->andWhere(['state' => $state]);
        } else {
            $query->andWhere([
                '<>', 'state', Message::STATUS_DELETE
            ]);
        }
        return new ActiveDataProvider([
            'query' => $query
        ]);
    }
}